//
//  ThemeDetailTableViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ThemeDetailTableViewController.h"
#import "ThemeDetailCell.h"
#import "ThemeCellDetailModel.h"
#import "ThemeTableViewController.h"

@interface ThemeDetailTableViewController ()<MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) NSMutableArray *cellDetailDataArry;
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@property (nonatomic, strong) AppDelegate *app;

@end

@implementation ThemeDetailTableViewController

#pragma mark - life cycle -

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
     [self setDetailData];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self addIndicatorView];
    [self setNavigationBar];
    [self addInternetObserver];
}

- (void)setNavigationBar
{
      self.navigationItem.title = self.titleStr;
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setDetailData];
 
}




#pragma mark - methods -
- (void)setDetailData
{
    if ([_app internetReachableOrNot]) {
        
        self.cellDetailDataArry = [NSMutableArray array];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.cellDetailUrl] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    NSURLSessionConfiguration *detailConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *detailSession = [NSURLSession sessionWithConfiguration:detailConfig];
    NSURLSessionDataTask *detailTask = [detailSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
            return ;
        }
        NSDictionary *detailDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *detailArray = [detailDic valueForKey:@"data"];
      
        for (NSDictionary *dic in detailArray) {
            ThemeCellDetailModel *model = [[ThemeCellDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.cellDetailDataArry addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.indicatorView stopAnimating];
            [self.tableView reloadData];
        });
    }];
    [detailTask resume];
    } else {
        [self.indicatorView stopAnimating];
        [self alertController];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellDetailDataArry.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ThemeCellDetailModel *model = self.cellDetailDataArry[indexPath.row];
    CGRect frame = CGRectMake(8, 175, kScreenWidth - 10, 0);
    frame.size.height = [ThemeDetailTableViewController cellHeightWithModel:model.desc font:14];
    return 240 + frame.size.height + 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *themeDetailIndentifier = @"themeDetailIndentifier";
    ThemeDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:themeDetailIndentifier];
    if (cell == nil) {
        cell = [[ThemeDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:themeDetailIndentifier];
    }
       if (self.cellDetailDataArry.count > 0) {
           ThemeCellDetailModel *model = self.cellDetailDataArry[indexPath.row];
        cell.titleTXT.text = model.title;
           cell.titleDetailTXT.text = model.desc;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: cell.titleDetailTXT.text];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:5];//调整行间距
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, cell.titleDetailTXT.text.length)];
        cell.titleDetailTXT.attributedText = attributedString;
           
        
        [cell.titleIMGView sd_setImageWithURL:[NSURL URLWithString:model.img]placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
           
           CGRect frame = CGRectMake(8, 210, kScreenWidth - 10, 0);
           frame.size.height = [ThemeDetailTableViewController cellHeightWithModel:model.desc font:14];
           cell.titleDetailTXT.frame = frame;

           
           [cell.titleDetailTXT sizeToFit];
}


    cell.userInteractionEnabled = NO;
    return cell;
}

+ (CGFloat)cellHeightWithModel:(NSString *)str font:(NSInteger)font
{
    // 计算字符串高度
    // 字号一定与lable相等
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName];
    CGRect lableFrame = [str boundingRectWithSize:CGSizeMake(kScreenWidth , 100000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    return lableFrame.size.height;
}


#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.frame = CGRectMake((kScreenWidth - 100) / 2, (kScreenHeight - 50) / 2, 100, 50);
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}



@end
